<template>
  <div class="loginBox">
    <el-row>
      <el-col :lg="24">
        <img src="@/assets/logo.png" style="width: 34px; margin-left: 15%;margin-top: 8px; float: left;">
        <div class="header">
          <span style="height: 50px; line-height: 50px; margin-left: 10px"><strong>{{ env.VITE_APP_TITLE }}</strong></span>
        </div>
      </el-col>
    </el-row>
    <el-row style="min-height: calc(100vh - 100px);" align="middle" justify="center">
      <el-col :span="24" class="box-align-center">
        <div class="rightBox animate__animated animate__slideInRight">
          <el-form
              :model="resetForm"
              :rules="rules"
              ref="ruleFormRef"
              style="overflow:hidden;"
              autocomplete="off"
              label-position="right"
              label-width="80"
              v-if="!isReset"
          >
            <el-form-item label-width="0">
              <img src="@/assets/logo.png" style="width: 36px">
              <span style="margin-left: 20px; font-size: 18px;"><strong>重置密码</strong></span>
            </el-form-item>

              <el-form-item label="用户名" prop="username">
                <el-input v-model="resetForm.username"  placeholder="请输入重置密码的用户名" style="height: 36px"></el-input>
              </el-form-item>
              <el-form-item label="邮箱" prop="email">
                <el-input v-model="resetForm.email" placeholder="请输入您注册时的邮箱" style="height: 36px"></el-input>
              </el-form-item>
              <el-form-item label="验证码" prop="code">
                <el-input v-model="resetForm.code" placeholder="请输入邮箱验证码" style="height: 36px">
                  <template #append>
                    <el-button @click="handleSendCode(resetForm.email)" :disabled="sms.disabled || resetForm.email == null">
                      <span v-if="!sms.disabled">发送邮箱验证码</span>
                      <span v-else>{{ sms.count }}s后重新发送</span>
                    </el-button>
                  </template>
                </el-input>
              </el-form-item>
            <el-form-item label="新 密 码" prop="password">
              <el-input v-model="resetForm.password" show-password autocomplete="new-password"
                        placeholder="请输入新密码" style="height: 36px"></el-input>
            </el-form-item>

            <el-form-item  label="确认密码" prop="confirmPassword" :error="errMsg" >
              <el-input v-model="resetForm.confirmPassword" show-password autocomplete="new-password"
                        placeholder="请再次输入密码确认" style="height: 36px"></el-input>
            </el-form-item>

              <el-form-item  label-width="10">
                <el-button class="login-button" type="primary" @click="handleReset(ruleFormRef)">重置密码</el-button>
              </el-form-item>
            <el-form-item style="float: right">
              <span class="register-text" @click="router.push({path:'/login'})">已想起密码，立即登录</span>
            </el-form-item>
          </el-form>
          <el-result
              icon="success"
              title="重置密码成功"
              sub-title="Password reset successful"
              v-else
          >
            <template #extra>
              <el-button type="primary" @click="router.push({path:'/login'})">立即登录</el-button>
            </template>
          </el-result>
        </div>
      </el-col>
    </el-row>
    <el-row>
      <el-col :lg="24">
        <div class="footer">
          <span style="height: 50px; line-height: 50px; margin-left: 10px; color: #555555">
            Powered By
            <a href="https://gitee.com/smmiaoya" target="_blank">喵喵</a>
          </span>
        </div>
      </el-col>
    </el-row>
  </div>

</template>

<script setup>

import {reactive, ref} from "vue";
import router from "../../../routers/index.js";
import {resetPassword, sendEmailCode,checkUserEmail,checkUsername } from "@/api/reset.js";
import {ElMessage} from "element-plus";

const sms = reactive({
  disabled: false,
  total: 60,
  count: 0
})
const errMsg = ref(null)
const isReset = ref(false)
const ruleFormRef = ref()
const isEmailOk = ref(false)
const resetForm = reactive({
  username: null,
  password: null,
  confirmPassword: null,
  email: null,
  code: null,
  uuid: null,
})
const rules = {
  username: [
    {required: true, message: '用户名不能为空', trigger: 'blur'},
    {validator: checkUserName, message: '用户名不存在', trigger: 'blur'},
    {pattern: /^[a-zA-Z0-9]{4,20}$/, message: '用户名长度为4 - 20位,只能由数字或字母构成'}
  ],
  email: [
    {required: true, message: '邮箱不能为空', trigger: 'blur'},
    {pattern: /^[a-zA-Z0-9_.-]+@[a-zA-Z0-9-]+(\.[a-zA-Z0-9-]+)*\.[a-zA-Z0-9]{2,6}$/, message: '请输入正确的邮箱'},
    {validator: checkEmail, message: '邮箱与该用户注册时的邮箱不一致!', trigger: 'blur'}
  ],
  password: [
    {required: true, message: '密码不能为空', trigger: 'blur'},
    {pattern: /(?![0-9A-Z]+$)(?![0-9a-z]+$)(?![a-zA-Z]+$)[0-9A-Za-z]{6,16}$/, message: '必须包含数字、大小写字母，长度6-16位'}
  ],
  confirmPassword: [
    {required: true, message: '密码不能为空', trigger: 'blur'},
    {validator: checkPassword, message: '两次密码不一致', trigger: 'blur'}
  ],
  code: [
    {required: true, message: '验证码不能为空', trigger: 'blur'},
    {pattern: /^[0-9A-Za-z]{6}$/, message: '请输入正确格式的验证码'}
  ]
}
const env = import.meta.env
const timerHandler = () => {
  sms.count = sms.total
  sms.disabled = true

  let timer = setInterval(() => {
    if (sms.count > 1 && sms.count <= sms.total) {
      sms.count--
    } else {
      sms.disabled = false
      clearInterval(timer)
    }
  }, 1000)
}

async function checkUserName(){
  let flag = false;
  await checkUsername(resetForm.username).then(res =>{
    flag = res.code == 200
  })
  return flag
}
async function checkEmail(){
  let flag = false;
  isEmailOk.value = false
  await checkUserEmail(resetForm.username,resetForm.email).then(res =>{
    if(res.code == 200) {
      flag = true
      isEmailOk.value = true
    }
  })
  return flag
}

function checkPassword(){
  return resetForm.password == resetForm.confirmPassword
}
function handleReset(formEl){
  if (!formEl) return
  formEl.validate((valid) =>{
    if(valid){
      resetPassword(resetForm).then(res =>{
        if(res.code == 200){
          isReset.value = true
        }
      })
    }else{
      ElMessage.error("请正确填写重置密码信息")
    }
  })
}

function handleSendCode(email){
  if(!isEmailOk){
    ElMessage.error("邮箱与该用户注册时的邮箱不一致！")
  }
  const reg = /^[a-zA-Z0-9_.-]+@[a-zA-Z0-9-]+(\.[a-zA-Z0-9-]+)*\.[a-zA-Z0-9]{2,6}$/
  if(reg.test(email)){
    sendEmailCode(email).then(res =>{
      resetForm.uuid = res.data.uuid
    })
    timerHandler()
  }else{
    ElMessage.error("邮箱格式不正确")
  }
}

</script>

<style lang="scss" scoped>
.loginBox {
  width: 100vw;
  min-height: 100vh;
  background: url(@/assets/bg.jpg) repeat-y;
  background-size: cover;
  .box-align-center {
    padding: 5%;
    display: flex;
    justify-content: center;
    align-items: center;
  }

  .header {
    height: 50px;
    line-height: 50px;
    background-color: white;
  }
  .footer{
    height: 50px;
    line-height: 50px;
    background-color: white;
    display: flex;
    justify-content: center;
    a{
      color: #31b267;
      text-decoration: none;
    }
  }

  .rightBox {
    width: 500px;
    //height: 700px;
    padding: 40px;
    padding-bottom: 0px;
    background-color: white;
    border-radius: 20px;
    box-shadow: 0 4px 16px 0 rgba(33, 37, 46, .12);

    .label-text {
      color: #606266;
      font-size: 16px
    }
    .login-button {
      width: 100%;
      margin-top: 10px;
      height: 35px;
    }
    .register-text{
      margin-top: 10px;
      color: gray;
      cursor: pointer;
    }
    .register-text:hover{
      color: #00b259;
    }

  }

}

.marbot5{
  margin-bottom: 5px;
}
.marbot10{
  margin-bottom: 10px;
}
.marbot20{
  margin-bottom: 20px;
}

</style>
